package config.java;

import java.io.File;
import java.util.Hashtable;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * xml配置文件解析<br>
 * 对以xml方式的配置文件，只支持以下简单的方式
 * 
 * <pre>
 *    &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
 *    &lt;root&gt;
 *    	&lt;config-key0&gt;value0&lt;/config-key0&gt;
 *    	&lt;config-key1&gt;value1&lt;/config-key1&gt;
 *    	&lt;config-key2&gt;value2&lt;/config-key2&gt;
 *    &lt;/root&gt;
 * </pre>
 * 
 * 在xml文件中一定要有一个根，且只能有一个根,如果不符合这种格式，会产生意想不到的数据
 * 
 * @author liao
 * 
 */
public class XmlConfig extends ParseConfig {

	@Override
	protected void parse(String alias, String file) {
		ConfigLog.debugLog("XML Config load file:" + file);
		ConfigValue value = ConfigValue.getInstance();
		ConfigBin b = value.getConfBin(alias);
		if (b == null)
			b = new ConfigBin();
		if (b != null) {
			b.setAlias(alias);
			b.setFile(file);
			b.setLoadTime(System.currentTimeMillis());
		}
		try {
			SAXHandler handler = new SAXHandler();
			SAXParserFactory saxparserfactory = SAXParserFactory.newInstance();
			SAXParser saxparser = saxparserfactory.newSAXParser();
			saxparser.parse(new File(file), handler);

			Hashtable<String, String> v = handler.getValue();
			if (v != null && v.size() > 0)
				value.setConfigValue(alias, v);
			ConfigLog.debugLog("XML Config file:" + file + " load success!");
			if (b != null)
				b.setStatus(1);
		} catch (Exception ex) {
			ConfigLog.errorLog("XML Config file:" + file + " load failed!");
			ConfigLog.errorLog(ex);
			if (b != null) {
				b.setStatus(-1);
				b.setError(ex.toString());
			}
		} finally {

			value.setConf(b);
		}
	}

}
